import React, { Component } from 'react';
import { messages, deepCopy } from 'share/common';
import { Form, Input, Button, message, Spin } from 'antd';
import InputLanguage from 'components/template/input-language';
import GrantRangeSelector from 'containers/data-center/report-distribution/grant-range-selector';
import CustomReportService
  from 'containers/data-center/report-management/custom-report/custom-report.service';

class NewCustomReport extends Component {
  constructor(props) {
    super(props);
    this.state = {
      spinning: false,
      data: {}, //自定义报表头信息
      loading: false,
      selectedGrantArray: [], //指定人员数组
      showMode: false, //其他类型报表 进入后 就是 showMode 不可更改任何东西
    };
    this.reportCategoryId = null;
  }

  componentWillMount() {

  }

  componentDidMount() {
    this.initData();
    this.getReportType();
  }

  componentWillUnmount() {

  }

  initData = () => {
    const { params } = this.props;
    if (params && params.id !== 'new') {
      if (params.reportType !== 'UD') {
        this.setState({ data: params, showMode: true });
      } else {
        this.setState({
          data: params,
          selectedGrantArray: (params.grants && params.grants.length) ? params.grants.map((item => item.user)) : []
        });
      }
    }
  };

  getReportType = () => {
    this.setState({ spinning: true });
    CustomReportService.getReportType()
      .then((res) => {
        if (res.status === 200) {
          let reportCategoryId;
          res && res.data && res.data.length && res.data.forEach((item) => {
            if (item.code === 'USER_DEFINE') {
              reportCategoryId = item.id;
            }
          });
          if (reportCategoryId) {
            this.reportCategoryId = reportCategoryId;
            this.setState({ spinning: false });
          }
        }
      });
  };

  onChangeSelectedGrantArray = (data) => {
    this.setState({ selectedGrantArray: data.result });
  };

  handleSave = (e) => {
    const { data } = this.state;
    const { params } = this.props;
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.setState({ loading: true });
        const { selectedGrantArray } = this.state;
        let paramsData = deepCopy(values);
        paramsData.reportName = values.reportName.name;
        paramsData.reportDesc = values.reportDesc.name;
        paramsData.reportCategoryId = this.reportCategoryId;
        paramsData.grants = selectedGrantArray.map(item => {
          return { grantDesc: '指定人员', grantProp: 'user', grantValue: item.userOID };
        });
        paramsData.i18n = {
          reportName: values.reportName.i18n,
          reportDesc: values.reportDesc.i18n
        };
        if (params && params.id !== 'new') {
          let updateData = Object.assign(data, paramsData);
          CustomReportService.updateCustomReport(updateData)
            .then((res) => {
              if (res.status === 200) {
                this.setState({ loading: false });
                message.success(messages('basic-10.key107')/*保存成功*/);
                this.props.close({needRefresh: true, key: 'default'});
              }
            })
            .catch(() => {
              this.setState({ loading: false });
            });
        } else {
          CustomReportService.addCustomReport(paramsData)
            .then((res) => {
              if (res.status === 200) {
                this.setState({ loading: false });
                message.success(messages('basic-10.key180')/*创建成功*/);
                this.props.close({needRefresh: true, key: 'default'});
              }
            })
            .catch(() => {
              this.setState({ loading: false });
            });
        }
      }
    });
  };

  render() {
    const { data, loading, selectedGrantArray, spinning, showMode } = this.state;
    const { getFieldDecorator } = this.props.form;

    return (
      <div className="new-custom-report">
        <Form className="new-form" onSubmit={this.handleSave}>
          {!showMode &&
          <Form.Item required label={messages('basic-10.key47')/*报表名称*/}>
            {getFieldDecorator('reportName', {
              rules: [InputLanguage.required],
              initialValue: { name: data.reportName, i18n: data.i18n ? data.i18n.reportName : [] }
            })(
              <InputLanguage
                disabled={showMode}
                placeholder={messages('common.max.characters.length',{arg1: 80})/*最多输入{arg1}个字符*/}
                maxLength={80}
              />
            )}
          </Form.Item>
          }
          {showMode &&
          <Form.Item label={messages('basic-10.key47')/*报表名称*/}>
            <Input value={data.reportName} disabled/>
          </Form.Item>
          }
          {!showMode &&
          <Form.Item label={messages('basic-10.key181')/*报表分类*/}>
            <Input value={messages('basic-10.key173')/*自定义报表*/} disabled/>
          </Form.Item>
          }
          {showMode &&
          <Form.Item label={messages('basic-10.key181')/*报表分类*/}>
            <Input value={data.reportCategoryName} disabled/>
          </Form.Item>
          }
          {!showMode &&
          <Form.Item required label={messages('basic-10.key182')/*报表描述*/}>
            {getFieldDecorator('reportDesc', {
              rules: [InputLanguage.required],
              initialValue: { name: data.reportDesc, i18n: data.i18n ? data.i18n.reportDesc : [] }
            })(
              <InputLanguage
                disabled={showMode}
                placeholder={messages('common.max.characters.length',{arg1: 80})/*最多输入{arg1}个字符*/}
                maxLength={80}
              />
            )}
          </Form.Item>
          }
          {showMode &&
          <Form.Item label={messages('basic-10.key182')/*报表描述*/}>
            <Input value={data.reportDesc} disabled/>
          </Form.Item>
          }
          {!showMode &&
          <div>
            <p>{messages('basic-10.key183')/*分配人员*/}</p>
            <GrantRangeSelector
              myTitle={messages('basic-10.key184')/*添加员工*/}
              grantCode={'user'}
              selectedGrantArray={selectedGrantArray}
              onChangeSelected={this.onChangeSelectedGrantArray}
            />
          </div>
          }
          {showMode &&
          <Form.Item label={messages('basic-10.key183')/*分配人员*/}>
            <Input value={messages('basic-10.key185')/*引用报表授权人员*/} disabled/>
          </Form.Item>
          }
          <div className="slide-footer">
            <Button disabled={showMode} type="primary" htmlType="submit"
                    loading={loading || spinning}>{messages('common.save')/*保存*/}</Button>
            <Button onClick={() => {
              this.props.close({needRefresh: false});
            }}>{messages('common.cancel')/*取消*/}</Button>
          </div>
        </Form>
      </div>
    );
  }
}

NewCustomReport.propTypes = {};

const WrappedNewCustomReport = Form.create()(NewCustomReport);

export default WrappedNewCustomReport;
